<template>
  <el-upload
    class="avatar-uploader"
    action="#"
    :show-file-list="false"
    :before-upload="beforeAvatarUpload"
    :http-request="uploadFn"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar">
    <svg-icon icon-class="upload" />
  </el-upload>
</template>

<script>
import { fileUpload } from '@/api'
export default {
  name: 'UploadImg',
  props: {
    value: {
      type: String,
      default: () => ''
    }
  },
  data() {
    return {
      imageUrl: ''
    }
  },
  watch: {
    value: {
      handler() {
        this.imageUrl = this.value
      },
      immediate: true
    }
  },
  methods: {
  // 图片上传
    beforeAvatarUpload(file) {
      const fileList = [
        'image/jpg',
        'image/png'
      ]
      const isJPG = fileList.includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 0.1

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 100kb!')
      }
      // console.log(file)
      return isJPG && isLt2M
    },
    async uploadFn(obj) {
      const formData = new FormData()
      formData.append(
        'fileName',
        obj.file
      )
      const res = await fileUpload(formData)
      this.imageUrl = res.data
      this.$emit('input', this.imageUrl)
    }
  }
}
</script>

<style lang="scss" scoped>
.avatar-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    font-size: 28px;
    width: 84px;
    height: 84px;
    line-height: 84px;
    text-align: center;
    color: #bac0cd;
    background-color: #f3f6fb;
    &:hover{
      border: 1px dashed black;
    }
  }
  .svg-icon{
    font-size: 25px;
  }
  .el-upload--text{
    font-size: 28px;
    color: #8c939d;
    width: 84px;
    height: 84px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 84px;
    height: 84px;
    display: block;
  }

</style>
